<?php

class Admin_ZipcodeController extends Zend_Controller_Action {

    public function init() {
        if (!Zend_Auth::getInstance()->hasIdentity()) {
            $this->_redirect("/admin/login");
        }
        $this->_helper->layout->setLayout("admin");
    }

    public function indexAction() {
        $zipDb = new Admin_Model_Zipcode();
        $form = new Admin_Form_Zipadd();
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $exists = $zipDb->isExists($values['zip']);
                if (!$exists) {
                    $zipDb->createNewZip(array(
                        'code' => $values['zip'],
                        'city_id' => $values['city']
                    ));
                    $this->_redirect("/admin/zipcode/add");
                } else {
                    $this->view->errorMessage = "This zipcode already exists.";
                }
            }
        }
        $allZipWithCityArray = $zipDb->getAllZipWithCityArray();
        $this->view->allData = $allZipWithCityArray;
    }

    public function updateAction() {
        $zipDb = new Admin_Model_Zipcode();
        $id = $this->getinputidAction();
        $form = new Admin_Form_ZipUpdate();
        $form->main($id);
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $exists = $zipDb->isExists($values['zip']);
                if (!$exists) {
                    $zipDb->updateZip(array(
                        'code' => $values['zip'],
                        'city_id' => $values['city'],
                            ), $values['id']);
                    $this->_redirect("/admin/zipcode/add");
                } else {
                    $this->view->errorMessage = "This zipcode already exists.";
                }
            }
        }
    }

    /**
     * Get ID.    
     */
    public function getinputidAction() {
        $filters = array(
            'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
        );
        $validators = array(
            'id' => array('Int')
        );
        $input = new Zend_Filter_Input($filters, $validators);
        $input->setData($this->getRequest()->getParams());
        $id = $input->id; //state id
        return $id;
    }

}

